package org.com.Uitls;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class MQexcelUtils {

    /**
     * 导出Excel文件
     * @param response HTTP响应
     * @param data 导出的数据列表
     * @param fileName 文件名
     * @param sheetName 工作表名
     * @param clazz 实体类类型
     */
    public static <T> void exportExcel(HttpServletResponse response, List<T> data, 
                                       String fileName, String sheetName, Class<T> clazz) {
        try {
            // 设置响应头 - 标准方式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            
            // 清除可能存在的缓存
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            response.setHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            
            // 防止中文乱码 - 使用标准的Content-Disposition格式
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName + ".xlsx");

            // 导出Excel
            EasyExcel.write(response.getOutputStream(), clazz)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet(sheetName)
                    .doWrite(data);
                    
            // 确保流被刷新和关闭
            response.getOutputStream().flush();
        } catch (ExcelGenerateException e) {
            log.error("Excel生成异常: {}", e.getMessage(), e);
            throw new RuntimeException("Excel生成失败: " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("IO异常: {}", e.getMessage(), e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage(), e);
        }
    }
}